/*************************************************************************
	> File Name: main.c
	> Author: Angel Criss
	> Blog: blog.abbycin.tk 
	> Created Time: Thu 03 Jul 2014 09:03:31 PM CST
 ************************************************************************/
/*
 * timer_create
 * timer_settime
 * timer_delete
 * timer_getoverrun
 */
#include "head.h"

extern void dealing(int,siginfo_t *,void *); // choose 15 line or 30 line which to comment

int main(int argc, char *argv[])
{
    if(argc<2)
    {
        printf("%s sec (nsec) value_of_id (another id)\n",argv[0]);
        _exit(0);
    }


    int i;
    struct sigevent evp;
    timer_t *timerid;
    struct itimerspec new_time; // declare a start time
   // void dealing(int,siginfo_t *,void *);

    struct sigaction act;

    timerid=calloc(argc-1,sizeof(timer_t)); // IMPORTANT!!!

    act.sa_sigaction=dealing;
    act.sa_flags=SA_SIGINFO;
    sigemptyset(&act.sa_mask);

    new_time.it_value.tv_sec=atoi(argv[1]); // expiration time in second
    /*if(argc>2)
    {
        new_time.it_value.tv_nsec=atoi(argv[2]); // expiration time in nanosecond
    }*/
    new_time.it_value.tv_nsec=0; // expiration time in nanosecond
    new_time.it_interval.tv_sec=0; // timer set only 1 time
    new_time.it_interval.tv_nsec=0; // the same as above

    if(sigaction(SIGALRM,&act,NULL)==-1)
    {
        perror("sigaction:");
        _exit(errno);
    }

    evp.sigev_notify=SIGEV_SIGNAL; // notify via signal
    evp.sigev_signo=SIGALRM; // invok sigaction by using SIGALRM
    //evp.sigev_value.sival_ptr=&timerid;

        for(i=0;i<argc-1;i++)
        {
            evp.sigev_value.sival_ptr=&timerid[i]; // allow handler to get ID of this timer

            if(timer_create(CLOCK_REALTIME,&evp,&timerid[i])==-1)
            {
                perror("timer_create:");
                _exit(errno);
            }

            if(timer_settime(timerid[i],0,&new_time,NULL)==-1)
            {
                perror("timer_settime:");
                 _exit(errno);
            }
        }

    for(;;)
    pause();

    if(timer_delete(timerid)==-1)
    {
        perror("timer_delete:");
        _exit(errno);
    }
    else
    {
        printf("\e[42mtimer deleted\e[0m\n");
        printf("all done\n");
        _exit(0);
    }
}
